package org.amse.tanks.player;

import org.amse.tanks.model.Model;
import org.amse.tanks.objects.Direction;
import org.amse.tanks.objects.Tank;
import org.amse.tanks.view.UIViewConstants;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;

public class NetworkPlayer implements Player, UIViewConstants, Runnable {
    private Tank myTank;
    private Model myModel;
    private Socket socket = null;
    private String myActions = "";
    private boolean areActionsValid = false;

    public NetworkPlayer(Model model, Tank tank, Socket socket) {
        myTank = tank;
        myModel = model;
        myModel.addTank(myTank);
        this.socket = socket;
        new Thread(this).start();
    }

    public void getMove(String str) {
        getMove();
    }

    public void getMove() {
        String str = "";
        str = getStr();

        if (str.contains(COMMAND_EXIT_CODE)) {
            //disconnect
        }
        if (str.contains(COMMAND_UP_CODE)) {
            myModel.moveTank(myTank.getId(), Direction.UP);
        }
        if (str.contains(COMMAND_LEFT_CODE)) {
            myModel.moveTank(myTank.getId(), Direction.LEFT);
        }
        if (str.contains(COMMAND_DOWN_CODE)) {
            myModel.moveTank(myTank.getId(), Direction.DOWN);
        }
        if (str.contains(COMMAND_RIGHT_CODE)) {
            myModel.moveTank(myTank.getId(), Direction.RIGHT);
        }
        if (str.contains(COMMAND_SHOOT_CODE)) {
            myModel.TankMakeShot(myTank.getId());
        }
    }

    private String getStr() {
        if (areActionsValid) {
            areActionsValid = false;
            return myActions;
        }
        return "";
    }

    public void run() {
        InputStream is = null;
        ObjectInputStream ois = null;
        String string = null;
        try {
            is = socket.getInputStream();
            ois = new ObjectInputStream(is);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            System.exit(-1);
        }

        while (true) {
            try {
                string = (String) ois.readObject();
            } catch (IOException e) {
                System.err.println("Couldn't get commands.");
                System.exit(-1);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                System.exit(-1);
            }

            myActions = string;
            areActionsValid = true;
        }
    }
}
